/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yuecai.modules.yc_cart.service;


import com.yuecai.modules.yc_cart.domain.YcCart;
import com.yuecai.modules.yc_cart.repository.YcCartRepository;
import com.yuecai.modules.yc_cart.service.dto.YcCartDto;
import com.yuecai.modules.yc_cart.service.dto.YcCartQueryCriteria;
import com.yuecai.modules.yc_cart.service.mapstruct.YcCartMapper;
import com.yuecai.modules.yc_cart.vo.YcCartVo;
import com.yuecai.modules.yc_goods.domain.YcGoods;
import com.yuecai.modules.yc_goods_sku.domain.YcGoodsSku;
import com.yuecai.modules.yc_goods_sku.repository.YcGoodsSkuRepository;
import com.yuecai.utils.FileUtil;
import com.yuecai.utils.QueryHelp;
import com.yuecai.utils.SecurityUtils;
import com.yuecai.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author dm
* @date 2020-06-27
**/
@Service
@RequiredArgsConstructor
public class YcCartService {

    private final YcCartRepository ycCartRepository;
    private final YcGoodsSkuRepository ycGoodsSkuRepository;
    private final YcCartMapper ycCartMapper;


    public Map<String,Object> queryAll(YcCartQueryCriteria criteria, Pageable pageable){
        Page<YcCart> page = ycCartRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<YcCart> content = page.getContent();
        List<YcCartVo> vos = new ArrayList<>();
        for (YcCart ycCart : content) {
            Long skuId = ycCart.getSkuId();
            Optional<YcGoodsSku> byId = ycGoodsSkuRepository.findById(skuId);
            if (byId.isPresent()){
                YcGoodsSku ycGoodsSku = byId.get();
                YcGoods ycGoods = ycGoodsSku.getYcGoods();
                if (ycGoods==null){
                    ycCartRepository.delete(ycCart);
                    continue;
                }
                Boolean status = ycGoods.getStatus();
                if (!status){
                    ycCartRepository.delete(ycCart);
                    continue;
                }
                YcCartVo ycCartVo = new YcCartVo();
                BeanUtils.copyProperties(ycGoodsSku,ycCartVo);
                BeanUtils.copyProperties(ycCart,ycCartVo);
                ycCartVo.setName(ycGoods.getName());
                ycCartVo.setToreInfo(ycGoods.getToreInfo());
                ycCartVo.setVipDiscount(ycGoods.getVipDiscount());
                ycCartVo.setImage(ycGoods.getImg());
                vos.add(ycCartVo);
            }else {
                ycCartRepository.delete(ycCart);
            }
        }
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",vos);
        map.put("totalElements",page.getTotalElements());
        return map;
    }


    public List<YcCartDto> queryAll(YcCartQueryCriteria criteria){
        return ycCartMapper.toDto(ycCartRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }


    @Transactional
    public YcCartDto findById(Long id) {
        YcCart ycCart = ycCartRepository.findById(id).orElseGet(YcCart::new);
        ValidationUtil.isNull(ycCart.getId(),"YcCart","id",id);
        return ycCartMapper.toDto(ycCart);
    }


    @Transactional(rollbackFor = Exception.class)
    public YcCartDto create(YcCart resources) throws Exception {
        String username = SecurityUtils.getCurrentUsername();
        Long aLong = Long.valueOf(username);
        //设置userID
        resources.setUserId(aLong);
        Long skuId = resources.getSkuId();
        Optional<YcGoodsSku> byId = ycGoodsSkuRepository.findById(skuId);



        if (byId.isPresent()){
            YcCart ycCart = findYcCart(aLong,skuId);
            YcGoodsSku ycGoodsSku = byId.get();
            Integer stock = ycGoodsSku.getStock();
            Integer count = resources.getGoodsNumber();
            resources.setGoodId(ycGoodsSku.getYcGoods().getId());
            if (ycCart!=null){
                resources.setGoodsNumber(count);
                resources.setId(ycCart.getId());
            }
            if (count>stock){
                throw new Exception("库存不足！您最多还能购买"+stock+"件，尽快下单吧！");
            }
        }else {
            throw new Exception("商品不存在！");
        }
        return ycCartMapper.toDto(ycCartRepository.save(resources));
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(YcCart resources) {
        YcCart ycCart = ycCartRepository.findById(resources.getId()).orElseGet(YcCart::new);
        ValidationUtil.isNull( ycCart.getId(),"YcCart","id",resources.getId());
        ycCart.copy(resources);
        ycCartRepository.save(ycCart);
    }

    /**
     * 查询用户购物车中是否有指定sku
     * @param username
     * @param skuId
     * @return
     */
    public YcCart findYcCart(Long username,Long skuId){

        return ycCartRepository.findByUserIdAndSkuId(username, skuId);
    }


    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ycCartRepository.deleteById(id);
        }
    }

    public void delete(Long id) {
        ycCartRepository.deleteById(id);
    }


    public void download(List<YcCartDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcCartDto ycCart : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("商品SKU", ycCart.getSkuId());
            map.put("个数", ycCart.getGoodsNumber());
            map.put("用户id", ycCart.getUserId());
            map.put("创建时间 时间戳", ycCart.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public HashMap skuCount(Long skuId) {
        String currentUsername = SecurityUtils.getCurrentUsername();
        Long userId = Long.valueOf(currentUsername);
        YcCart byUserIdAndSkuId = ycCartRepository.findByUserIdAndSkuId(userId, skuId);
        if (byUserIdAndSkuId==null){
            return null;
        }
        Long goodId = byUserIdAndSkuId.getGoodId();
        List<YcCart> byUserIdAndGoodId = ycCartRepository.findByUserIdAndGoodId(userId, goodId);
        List<Integer> collect = byUserIdAndGoodId.stream().map(YcCart::getGoodsNumber).collect(Collectors.toList());
        long sum = collect.stream().reduce(Integer::sum).orElse(0);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("skuCount",byUserIdAndSkuId.getGoodsNumber());
        map.put("goodCount",sum);
        return map;
    }
}